package com.reconcile.phone.common.utils;

import com.aliyun.dypnsapi20170525.Client;
import com.aliyun.dypnsapi20170525.models.GetMobileRequest;
import com.aliyun.dypnsapi20170525.models.GetMobileResponse;
import com.aliyun.dypnsapi20170525.models.GetMobileResponseBody;
import com.aliyun.teautil.models.RuntimeOptions;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 一键登录工具
 *
 * @author zxl
 * @since 2024/1/22
 */
@Component
@Slf4j
public class AppOneClickUtil {

    @Resource
    private Client client;

    private static Client staticClient;

    @PostConstruct
    public void init() {
        staticClient = client;
    }

    /**
     * 一键登陆
     *
     * @param accessToken 阿里云token
     * @return 手机号码
     */
    public static String login(String accessToken) {
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        GetMobileRequest getMobileRequest = new GetMobileRequest().setAccessToken(accessToken);
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            GetMobileResponse mobileWithOptions = staticClient.getMobileWithOptions(getMobileRequest, runtime);
            GetMobileResponseBody body = mobileWithOptions.getBody();
            if (!body.getCode().equalsIgnoreCase("ok")) {
                throw new RuntimeException(body.getMessage());
            }
            return body.getGetMobileResultDTO().getMobile();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("手机号获取失败", e);
        }
    }
}
